package com.guoxue.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * Cookie工具类
 * @author young
 * @version 2016.07.12
 */
public class CookieUtils {
	/**
	 *  按name查找cookie，isRemove是否删除当前这个cookie信息
	 */
	public static String getCookie(HttpServletRequest req , HttpServletResponse resp , String name , boolean isRemove){
		String value = null;
		Cookie[] cookies = req.getCookies();
		if(cookies != null){
			for(Cookie cookie : cookies){
				if (cookie.getName().equals(name)){
					try {
						value = URLDecoder.decode(cookie.getValue(),"utf-8");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			if (isRemove) {
				cookie.setMaxAge(0);
				resp.addCookie(cookie);
			   }
			}
		}
		return value;
	}
	/**
	 * 设置cookie的工具方法  value:所需要在cookie中存放的值 name:cookie的名称 age:存放时间 小于0 为关闭浏览器则清楚，大于0单位为小时。等于0不存放cookie
	 * @param
	 * @param 
	 * @param 
	 */
	public static void setCookie(HttpServletResponse resp,String value,String name, int age){
		Cookie cookie = new Cookie(name, null); 
		cookie.setMaxAge(age*60*60);
		cookie.setPath("/");
		try {
			cookie.setValue(URLEncoder.encode(value,"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		resp.addCookie(cookie);
	}
	
}
